<template>
  <el-menu default-active="2" :collapse="collapsed" collapse-transition router :default-active="$route.path"
           unique-opened class="el-menu-vertical-demo" background-color="#334157" text-color="#fff"
           active-text-color="#ffd04b">
    <div class="logobox" @click="toHome">
      <img class="logoimg" src="../assets/img/logo.png" alt="">
    </div>
    <el-submenu v-for="menu in allmenu" :key="menu.menuid" :index="menu.menuname">
      <template slot="title">
        <i class="iconfont" :class="menu.icon"></i>
        <span>{{menu.menuname}}</span>
      </template>
      <el-menu-item-group>
        <el-menu-item v-for="chmenu in menu.menus" :index="'/'+chmenu.url" :key="chmenu.menuid">
          <i class="iconfont" :class="chmenu.icon"></i>
          <span>{{chmenu.menuname}}</span>
        </el-menu-item>
      </el-menu-item-group>
    </el-submenu>
  </el-menu>
</template>
<script>
  import {menu} from '../api/userMG'

  export default {
    name: 'leftnav',
    data() {
      return {
        collapsed: false,
        allmenu: []
      }
    },
    // 创建完毕状态(里面是操作)
    created() {
      menu().then(res => {
        this.allmenu = [];
        for (let i = 0; i < res.data.length; i++) {
          let datum = res.data[i];

          if(datum.parentId === 0) {
            this.allmenu.push({
              id: datum.menuId,
              icon: datum.icon,
              menuname: datum.name,
              hasThird: null,
              url: null,
              menus: [

              ]
            });
          }
        }
        for (let i = 0; i < res.data.length; i++) {
          let datum = res.data[i];
          if (datum.parentId !== 0) {
            for (let j = 0; j < this.allmenu.length; j++) {
              let datumElement = this.allmenu[j];
              if(datumElement.id === datum.parentId) {
                this.allmenu[j].menus.push(
                  {
                    icon: datum.icon,
                    menuname: datum.name,
                    hasThird: 'N',
                    url: datum.url,
                    menus: null
                  }
                )
              }
            }
          }
        }
      }).catch(err => {
        this.$message.error('菜单加载失败，请稍后再试！')
      });
      // 监听
      this.$root.Bus.$on('toggle', value => {
        this.collapsed = !value
      })
    },
    methods: {
      toHome() {
        this.$router.push({path: '/home'})
      }
    }
  }
</script>
<style>
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 240px;
    min-height: 400px;
  }

  .el-menu-vertical-demo:not(.el-menu--collapse) {
    border: none;
    text-align: left;
  }

  .logobox {
    height: 40px;
    line-height: 40px;
    color: #9d9d9d;
    font-size: 20px;
    text-align: center;
    padding: 20px 0px;
  }

  .logoimg {
    height: 40px;
  }
</style>
